package com.pronhub.cloud.shop.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.pronhub.shop.cloud.Result;
import com.pronhub.cloud.shop.util.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class TokenRefreshFilter extends ZuulFilter {

    @Autowired
    private TokenFeignApi tokenFeignApi;
    //过滤的是POST的请求
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }
    //相同的过滤器优先级顺序
    //谁先后的问题
    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //是否存在Cookie  如果存在Cookie 返回true 需要过滤
        //如果不是 返回flase 不需要过滤
        RequestContext context = RequestContext.getCurrentContext();//获取上下文的内容
        HttpServletRequest request = context.getRequest();
        String token = CookieUtil.getCookie(request,CookieUtil.TOKEN_NAME);
        //如果没有就返回一个true
        if (!StringUtils.isEmpty(token)){
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        //同时刷新两边时间
        RequestContext context = RequestContext.getCurrentContext();//获取上下文的内容
        HttpServletRequest request = context.getRequest();
        String token = CookieUtil.getCookie(request,CookieUtil.TOKEN_NAME);
        Result<Boolean> result = tokenFeignApi.refreshToken(token);
        if (request!=null && result.hasError() && result.getData()){
            //更新Redis
            CookieUtil.addCookie(context.getResponse(),CookieUtil.TOKEN_NAME,token,CookieUtil.TOKEN_SECONDS);
        }

        return null;
    }
}
